import type { HtmlTitle } from "@/types/knows/HtmlTitle";
import TurndownService from "turndown";
import { marked } from "marked"; // 如果需要解析 Markdown
/**
 * 获取html中由H1H2H3组成的标题
 * @param html - 大段的HTML字符串
 * @returns 包含标题名称、标签、层级和顺序号的数组
 */
const getTitles = (html: string): Array<HtmlTitle> => {
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, "text/html");

  // 查找所有的 H1, H2, H3 标签
  const headings = Array.from(doc.querySelectorAll("h1, h2, h3"));

  // 提取每个非空标题的信息并分配顺序号
  const titles: Array<HtmlTitle> = [];
  let index = 0;

  headings.forEach((heading) => {
    const titleText = heading.textContent?.trim() || "";
    index++;
    if (titleText.length > 0) {
      titles.push({
        title: titleText,
        mark: heading.tagName,
        level: parseInt(heading.tagName.replace("H", ""), 10),
        index: index,
      });
    }
  });

  return titles;
};
/**
 * 删除html标签返回纯文本
 * @param html
 * @returns
 */
const removeHtmltags = (html: string) => {
  return html.replace(/<[^>]+>/g, "");
};

/**
 * html转markdown
 * @param html
 * @returns
 */
const getMarkDown = (html: string) => {
  const turndownService = new TurndownService();
  return turndownService.turndown(html);
};

/**
 * 转换为html
 * @param text markDown文本
 * @returns
 */
const getHtmlByMarkDown = (text: string) => {
  return marked.parse(text) as string;
};

export default { getTitles, removeHtmltags, getMarkDown, getHtmlByMarkDown };
